import * as visitorService from '../../services/visitor';

export default {
    namespace: 'visitor',
    state: {
        visitorList : [],
        current : 1,
        currentSize : 10,
        total : 0, 
        modalVisible : false,
        modalType : 'create',
        newKey : '', 
        eModalVisible: false,
        lModalVisible: false,
        itemId: null,
    },
    reducers: {
        qryVisitorByParamsSuc(state, { payload }) {
            return { ...state, ...payload };
        },
        showModal (state, { payload }) {
            return { ...state, ...payload, newKey : new Date().getTime() + '' , modalVisible: true }
        },
        hideModal (state) {
            return { ...state, modalVisible: false, newKey : new Date().getTime() + '' }
        },
        showEModal (state, { payload }) {
            return { ...state, itemId: payload, newKey: new Date().getTime() + '' , eModalVisible: true }
        },
        hideEModal (state) {
            return { ...state, eModalVisible: false, newKey : new Date().getTime() + '' }
        },
        showLModal (state, { payload }) {
            return { ...state, itemId: payload, newKey: new Date().getTime() + '' , lModalVisible: true }
        },
        hideLModal (state) {
            return { ...state, lModalVisible: false, newKey : new Date().getTime() + '' }
        },
    },
    effects: {
        *qryVisitorByParams({ payload },{ call, put }) {
            const { body } = yield call(visitorService.qryVisitorByParams,payload);
            yield put({ type: 'qryVisitorByParamsSuc', payload: { visitorList:body.data, current:body.current, currentSize:body.size, total:body.iTotalRecords }});
        },
        *create({ payload },{ call, put }){
            const { body } = yield call(visitorService.create,payload);
             yield put({ type: 'hideModal'});
             yield put({ type: 'qryVisitorByParams' ,payload:{}});
        },
        *entry({ payload },{ call, put }){
            const { body } = yield call(visitorService.entry,payload);
            yield put({ type: 'hideEModal'});
            yield put({ type: 'qryVisitorByParams' ,payload:{}});
        },
        *leave({ payload },{ call, put }){
            const { body } = yield call(visitorService.leave,payload);
            yield put({ type: 'hideLModal'});
            yield put({ type: 'qryVisitorByParams' ,payload:{}});
        },
    },
    subscriptions: {
        setup({ dispatch, history }) {
            return history.listen(({ pathname }) => {
              if (pathname === '/visitor') {
                dispatch({ type: 'qryVisitorByParams', payload:{}});
              }
            });
        },
    },
};